﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web.Script.Serialization;

public partial class Json : System.Web.UI.Page
{
    private const string CONNECTION_STRING =
             "Data Source=SHEEPY\\SQLEXPRESS;User ID=ltinteractive;Password=ltinteractive;Trusted_Connection=False;Initial Catalog=laostraveller";


    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Expires = -1;

        //http://weblogs.asp.net/hajan/archive/2010/07/23/javascriptserializer-dictionary-to-json-serialization-and-deserialization.aspx

        var dict = new Dictionary<string, object>();
        
        try
        {
            using (var sqlConn = new SqlConnection(CONNECTION_STRING))
            {
                const string sql = "select * from customer";

                sqlConn.Open();
                using (var insertCmd2 = new SqlCommand(sql, sqlConn))
                {
                    SqlDataReader myReader = insertCmd2.ExecuteReader(CommandBehavior.CloseConnection);
                    int rowCounter = 0;
                    while (myReader.Read())
                    {
                        var columnAttributes = new object[myReader.FieldCount];
                        myReader.GetValues(columnAttributes);

                        var objNSa = new object[myReader.FieldCount];

                        for (int x = 0; x < myReader.FieldCount; x++)
                        {
                            if (columnAttributes[x] is DateTime)
                            {
                                objNSa[x] = (((DateTime)columnAttributes[x]).ToShortDateString());
                            }
                            else
                            {
                                objNSa[x] = columnAttributes[x]; 
                            }
                        }
                        dict.Add("row" + rowCounter, objNSa);
                        rowCounter++;
                    }
                    myReader.Close();
                }
                sqlConn.Close();
            }
        }
        catch (Exception)
        {
        }

        var builder = new StringBuilder();
        new JavaScriptSerializer().Serialize(dict, builder);
        Response.Write(builder.ToString());
    }
}